import logging
import os
import sys
import time
from logging.handlers import TimedRotatingFileHandler
from datetime import datetime

# 获取当前文件路径，拼接json配置文件，生成路径，以供后面使用
path = os.path.dirname(__file__)
# log_file_path = path+'/log/' + time.strftime('%Y-%m-%d') + '.log'
log_file_path = path+'/log/' + 'rslog.log'


class MyLogger:
    def __init__(self, log_file):
        # 如果日志文件存储目录不存在，则在项目下创建目录
        if not os.path.exists(path+'/log/'):
            os.makedirs(path+'/log/')

        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.INFO)

        formatter = logging.Formatter('%(asctime)s - PID:%(process)d - %(levelname)s - %(message)s')

        # 创建一个文件处理器，将日志写入到文件中
        # file_handler = logging.FileHandler(log_file)
        # 创建一个TimedRotatingFileHandler，每天创建一个新的日志文件
        file_handler = TimedRotatingFileHandler(log_file, when='midnight', interval=1, backupCount=5, encoding='utf-8')
        file_handler.setFormatter(formatter)
        self.logger.addHandler(file_handler)

        # 创建一个控制台处理器，将日志输出到控制台
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)
        self.logger.addHandler(console_handler)

    def log_info(self, message):
        self.logger.info(message)

    def log_warning(self, message):
        self.logger.warning(message)

    def log_error(self, message):
        self.logger.error(message)

    def log_critical(self, message):
        self.logger.critical(message)


# 实例化日志类，将当天的日期用作日志文件的名称
logger = MyLogger(log_file_path)

if __name__ == '__main__':
    # 使用自定义的日志记录器
    # logger = MyLogger('log/example.log')
    logger.log_info('This is an info message')
    logger.log_warning('This is an info message')
    logger.log_error('This is an error message')
    logger.log_critical('This is an error message')
